#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# pip3 install PyJWT
import jwt
import time
import requests
from http.client import HTTPConnection
HTTPConnection.debuglevel=1

URL = 'https://api.storekit.itunes.apple.com/inApps/v1/notifications/test'
SANDBOX_URL = 'https://api.storekit-sandbox.itunes.apple.com/inApps/v1/notifications/test'

NOTIFY_HISTORY_SANDBOX_URL = 'https://api.storekit-sandbox.itunes.apple.com/inApps/v1/notifications/history'
# 读取密钥文件证书内容
f = open("./SubscriptionKey_65CK3LSXM7.p8")
key_data = f.read()
f.close()
# JWT Header
header = {
    "alg": "ES256",
    "kid": "65CK3LSXM7",    #您在 App Store Connect 中的私钥 ID（例如2X9R4HXF34：）
    "typ": "JWT"
}
# JWT Payload
payload = {
    "iss": "69a6de82-0563-47e3-e053-5b8c7c11a4d1",  #您在 App Store Connect 中的密钥页面中的发行者 ID（例如：" 57246542-96fe-1a63-e053-0824d011072a"）
    "iat": int(time.time()),            #您发行令牌的时间，以 UNIX 时间表示（例如1623085200：）
    "exp": int(time.time()) + 60 * 60, # 60 minutes timestamp
    "aud": "appstoreconnect-v1",
    "bid": "com.td.watcherofrealms"
}

# JWT token
token = jwt.encode(headers=header, payload=payload, key=key_data, algorithm="ES256")
print("JWT Token:", token)

http_header = {
    "Authorization": f"Bearer {token}",
}
print(http_header)
# http_header = f "Bearer {token}"
# http_header = f'Bearer [%s]' %token
r = requests.post(SANDBOX_URL, headers=http_header, verify=False)
# r = requests.post(URL, headers=http_header, verify=False)
print(r.text)
#-------------------------------------------------------------------------
# data = {
        # "startDate": int ((time.time() -15 *3600 * 24) *1000),
        # "endDate": int (time.time() *1000),
        # "NotificationType": "DID_RENEW",
# }
# r = requests.post(NOTIFY_HISTORY_SANDBOX_URL, headers=http_header, json=data,verify=False)
# print(r.text)
